<template>
  <div class="login">
    <!-- header -->
    <header class="header">
      <router-link to="/home">
        <van-icon name="arrow-left" />
      </router-link>
      <span class="header-titile">{{ isLogin == 'login' ? '用户名登录' : isLogin == 'msgLogin' ? '短信登录' : '注册' }}</span>
      <i></i>
    </header>
    <!-- logo -->
    <div class="newbee-logo">
      <img src="../assets/home/logo.png" class="" alt="" />
    </div>
    <!-- 用户名登录表单 -->
    <van-form @submit="onSubmit" class="login-from" v-if="isLogin == 'login'">
      <van-field v-model="uname1" name="账号" label="账号" placeholder="请输入用户名或手机号" :rules="[{ required: true, message: '请输入正确的账号', pattern: /^.{5,16}$/, trigger: 'onBlur' }]" />
      <van-field v-model="password1" type="password" name="密码" label="密码" placeholder="请输入密码" :rules="[{ required: true, message: '请输入6-16位密码', pattern: /^.{6,16}$/, trigger: 'onBlur' }]" />
      <!-- 验证码 -->
      <div class="verify">
        <Verify ref="loginVerifyRef" :showButton="false" @error="error" @success="success" :width="'100%'" :height="'40px'" :fontSize="'16px'" :type="2"></Verify>
      </div>
      <!-- 切换短信登录,注册状态,登录按钮 -->
      <div class="submit">
        <div class="to-login" @click="changeType('msgLogin')">短信登录</div>
        <div class="to-login" @click="changeType('register')">立即注册</div>
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <!-- 短信登录 -->
    <van-form @submit="onSubmit" class="login-from" v-else-if="isLogin == 'msgLogin'">
      <van-field v-model="msgphone" name="msgphone" label="手机号" placeholder="请输入手机号" :rules="[{ required: true, message: '请输入正确的手机号', pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/, trigger: 'onBlur' }]" />
      <div class="msgmsg">
        <van-field class="msg1" v-model="msgCode" type="text" name="msgCode" label="验证码" placeholder="请输入验证码" :rules="[{ required: true, message: '请输入4数字', pattern: /^\d{4}$/, trigger: 'onBlur' }]" />
        <p @click="sendmsg" v-if="msgIsSend">发送</p>
        <p v-else>{{ msgNumber }}</p>
      </div>
      <!-- 切换用户名登录,注册状态,登录按钮 -->
      <div class="submit">
        <div class="to-login" @click="changeType('login')">用户名登录</div>
        <div class="to-login" @click="changeType('register')">立即注册</div>
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <!-- 注册表单 -->
    <van-form @submit="onSubmit" class="login-from" v-else>
      <van-field
        v-model="phone"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请输入正确的手机号',
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            trigger: 'onBlur'
          }
        ]"
      />
      <van-field
        v-model="uname2"
        name="用户名"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[
          {
            required: true,
            message: '请输入6-16位数字或字母',
            pattern: /^.{5,16}$/,
            trigger: 'onBlur'
          }
        ]"
      />
      <van-field class="email-1" v-model="email" type="text" name="email" label="邮箱号" placeholder="请输入邮箱" :rules="[{ required: true, message: '请输入正确格式邮箱', pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, trigger: 'onBlur' }]" />
      <div class="msgmsg">
        <van-field class="msg1" v-model="emailCode" type="text" name="emailCode" label="验证码" placeholder="请输入验证码" :rules="[{ required: true, message: '请输入4数字', pattern: /^\d{4}$/, trigger: 'onBlur' }]" />
        <p @click="verifyemail" v-if="emailIsSend">发送</p>
        <p v-else>{{ emailNumber }}</p>
      </div>
      <van-field v-model="password2" type="password" name="密码" label="密码" placeholder="请输入密码" :rules="[{ required: true, message: '请输入6-16位密码', pattern: /^.{6,16}$/, trigger: 'onBlur' }]" />
      <!-- 切换用户名登录,登录按钮 -->
      <div class="submit">
        <div class="to-login" @click="changeType('login')">已有登录账号</div>
        <van-button round block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
// 引入axios请求函数
import { login, msgLogin, register, SMSverification, sendEmailCode } from '../server/user.js'
// 引入验证码模块
import Verify from 'vue2-verify'

export default {
  // 注册验证码组件为子组件
  components: {
    Verify
  },
  data() {
    return {
      clock: null, //准备一个定时器
      isLogin: 'login', //判断登录or注册
      uname1: '', //登录用户名
      password1: '', //登录密码
      phone: '', //注册手机号
      uname2: '', //注册用户名
      password2: '', //注册密码
      email: '', //邮箱
      emailCode: '', //邮箱验证码
      msgphone: '', //短信登录手机号
      msgCode: '', //短信验证码
      msgIsSend: true, //短信验证码发送是否显示
      msgNumber: 59, //短信验证码可发送的倒计时
      emailIsSend: true, //邮箱验证码发送是否显示
      emailNumber: 59, //邮箱验证码可发送的倒计时
      verify: null //图形验证码是否正确
    }
  },
  methods: {
    // 邮箱验证码倒计时
    emailDoLoop() {
      // 如果数值大于0则--
      if (this.emailNumber > 0) {
        this.emailNumber--
      } else {
        // 否则清除定时器,恢复按钮并重置数值
        clearInterval(this.clock)
        this.emailIsSend = true
        this.emailNumber = 59
      }
    },
    //发送邮箱验证码
    verifyemail() {
      // 邮箱不为空
      if (this.email != '') {
        // 取消发送按钮
        this.emailIsSend = false
        // 开启定时器,数值每秒-1
        this.clock = setInterval(this.emailDoLoop, 1000)
        sendEmailCode(this.email)
          .then(result => {
            console.log(result)
            this.$toast.success('验证码发送成功')
          })
          .catch(() => {
            this.$toast.fail('请检查邮箱格式')
          })
      } else {
        this.$toast.fail('请先输入邮箱账号')
      }
    },
    // 短信验证码倒计时
    msgDoLoop() {
      // 如果数值大于0则--
      if (this.msgNumber > 0) {
        this.msgNumber--
      } else {
        // 否则清除定时器,恢复按钮并重置数值
        clearInterval(this.clock)
        this.msgIsSend = true
        this.msgNumber = 59
      }
    },
    //发送短信验证码按钮
    sendmsg() {
      // 手机号不为空
      if (this.msgphone != '') {
        // 取消发送按钮
        this.msgIsSend = false
        // 开启定时器,数值每秒-1
        this.clock = setInterval(this.msgDoLoop, 1000)
        // 发送请求,获取验证码
        SMSverification(this.msgphone)
          .then(result => {
            this.$toast.success('验证码发送成功:' + result)
            console.log(result)
          })
          .catch(() => {
            this.$toast.fail(`获取验证码失败`)
          })
      } else {
        this.$toast.fail(`请输入手机号`)
      }
    },
    // 执行验证码的验证
    loginCheck() {
      this.$refs.loginVerifyRef.$refs.instance.checkCode() // 通过 this.verify 知道验证码是否填写正确
    },
    // 验证码通过
    success(obj) {
      this.verify = true
    },
    // 验证码不通过
    error(obj) {
      this.verify = false
      obj.refresh() // 刷新验证码
    },
    // 更改登录/注册状态
    changeType(type) {
      this.isLogin = type
      this.verify = false
      this.uname1 = ''
      this.password1 = ''
      this.phone = ''
      this.uname2 = ''
      this.password2 = ''
      this.email = ''
      this.msgphone = ''
      this.msgCode = ''
      this.emailCode = ''
    },
    // 提交
    onSubmit() {
      // 执行用户名登录请求
      if (this.isLogin == 'login') {
        // 验证用户名/密码格式是否正确
        this.loginCheck()
        if (!this.verify) {
          this.$toast.fail('验证码未填写或填写错误!')
          return
        }
        login(this.uname1, this.password1)
          .then(result => {
            localStorage.setItem('token', result)
            this.$toast.success('登录成功')
            this.$router.push('/')
          })
          .catch(ok => {
            if (ok == -2) this.$toast.fail('账户已被禁用,请联系管理员')
            else if (ok == -3) this.$toast.fail('账户已被注销,无法登录')
            else this.$toast.fail('账号或密码错误,登录失败')
            this.uname1 = ''
            this.password1 = ''
          })
      }
      // 执行短信验证码登录请求
      if (this.isLogin == 'msgLogin') {
        msgLogin(this.msgphone, this.msgCode)
          .then(result => {
            localStorage.setItem('token', result)
            this.$toast.success('登录成功')
            this.$router.push('/')
          })
          .catch(err => {
            if (err == -1) this.$toast.fail('验证码错误')
            else if (err == -2) this.$toast.fail('账户已被禁用,请联系管理员')
            else if (err == -3) this.$toast.fail('账户已被注销,无法登录')
            else if (err == -5) this.$toast.fail('手机号不存在,请先注册')
            this.msgphone = ''
          })
      }
      // 执行注册请求
      if (this.isLogin == 'register') {
        register(this.phone, this.uname2, this.password2, this.email, this.emailCode)
          .then(() => {
            this.$toast.success('注册成功,已为您跳转登录页')
            this.isLogin = 'login'
          })
          .catch(ok => {
            if (ok == -2) this.$toast.fail('手机号已被注册')
            else if (ok == -3) this.$toast.fail('验证码输入错误,请检查')
            else this.$toast.fail('注册失败.请检查后重试')
          })
      }
    }
  }
}
</script>
<style lang="scss">
@import './scss/login.scss';
</style>
